package com.mxpio.erp.technology.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.mxpio.erp.common.ItemGroupUtil;
import com.mxpio.erp.common.technology.entity.*;
import com.mxpio.erp.common.technology.service.*;
import com.mxpio.erp.common.technology.vo.ItemWithSubExtendsVO;
import com.mxpio.erp.technology.policy.impl.ItemDeletePolicy;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.mxpioframework.common.util.BeanReflectionUtils;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "ItemController", description = "物料接口")
@RestController
@RequestMapping("/erp/common/item/")
public class ItemController {
	
	@Autowired
	private ItemService itemSerivce;
	@Autowired
	private ItemGroupService itemGroupsSerivce;
	@Autowired
	private ItemDeletePolicy itemDeletePolicy;
	@GetMapping("list")
	@Operation(summary = "物料列表", description = "获取物料列表", method = "GET")
	public Result<List<Item>> list(Criteria criteria) throws UnsupportedEncodingException {
		List<Object> criterions = criteria.getCriterions();
		List<String> groupCodes = new ArrayList<>();
		if (!criterions.isEmpty()){
			Iterator<Object> iterator = criterions.iterator();
			Criteria c = Criteria.create();
			List<ItemGroup> itemGroups = itemGroupsSerivce.tree(ItemGroup.class, c);
			while(iterator.hasNext()){
				Object next = iterator.next();
				if (next instanceof SimpleCriterion){
					SimpleCriterion simpleCriterion = (SimpleCriterion)next;
					if (StringUtils.equals(simpleCriterion.getFieldName(),"itemGroupCode")){
						String value = (String) simpleCriterion.getValue();
						if (itemGroups.size()>0){
							ItemGroup itemGroupFromList = ItemGroupUtil.getItemGroupFromList(itemGroups, value);
							ItemGroupUtil.getAllGroupCodeFromItemGroup(groupCodes,itemGroupFromList);
						}
						if (groupCodes.size()>0){
							iterator.remove();
						}
						break;
					}
				}
			}

		}
		if (groupCodes.size()>0){
			criteria.addCriterion("itemGroupCode",Operator.IN,groupCodes);
		}
		List<Item> items = itemSerivce.list(Item.class, criteria);
		return Result.OK(items);
	}
	
	@GetMapping("page")
	@Operation(summary = "物料列表", description = "获取物料列表", method = "GET")
	@Transactional
	public Result<Page<Item>> page(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
		Pageable page = PageRequest.of(pageNo-1, pageSize);
		List<Object> criterions = criteria.getCriterions();
		List<String> groupCodes = new ArrayList<>();
		if (!criterions.isEmpty()){
			Iterator<Object> iterator = criterions.iterator();
			Criteria c = Criteria.create();
			List<ItemGroup> itemGroups = itemGroupsSerivce.tree(ItemGroup.class, c);
			while(iterator.hasNext()){
				Object next = iterator.next();
				if (next instanceof SimpleCriterion){
					SimpleCriterion simpleCriterion = (SimpleCriterion)next;
					if (StringUtils.equals(simpleCriterion.getFieldName(),"itemGroupCode")){
						String value = (String) simpleCriterion.getValue();
						if (itemGroups.size()>0){
							ItemGroup itemGroupFromList = ItemGroupUtil.getItemGroupFromList(itemGroups, value);
							ItemGroupUtil.getAllGroupCodeFromItemGroup(groupCodes,itemGroupFromList);
						}
						if (groupCodes.size()>0){
							iterator.remove();
						}
						break;
					}
				}
			}

		}
		if (groupCodes.size()>0){
			criteria.addCriterion("itemGroupCode",Operator.IN,groupCodes);
		}
		Page<Item> items = itemSerivce.listPage(Item.class, page, criteria);
		return Result.OK(items);
	}

	@GetMapping("pageWithSubExtends")
	@Operation(summary = "物料列表带子表扩展信息", description = "获取物料列表带子表扩展信息（分页）", method = "GET")
	@Transactional(readOnly = true)
	public Result<Page<ItemWithSubExtendsVO>> pageWithExtends(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
		Pageable page = PageRequest.of(pageNo-1, pageSize);
		List<Object> criterions = criteria.getCriterions();
		List<String> groupCodes = new ArrayList<>();
		if (!criterions.isEmpty()){
			Iterator<Object> iterator = criterions.iterator();
			Criteria c = Criteria.create();
			List<ItemGroup> itemGroups = itemGroupsSerivce.tree(ItemGroup.class, c);
			while(iterator.hasNext()){
				Object next = iterator.next();
				if (next instanceof SimpleCriterion){
					SimpleCriterion simpleCriterion = (SimpleCriterion)next;
					if (StringUtils.equals(simpleCriterion.getFieldName(),"itemGroupCode")){
						String value = (String) simpleCriterion.getValue();
						if (itemGroups.size()>0){
							ItemGroup itemGroupFromList = ItemGroupUtil.getItemGroupFromList(itemGroups, value);
							ItemGroupUtil.getAllGroupCodeFromItemGroup(groupCodes,itemGroupFromList);
						}
						if (groupCodes.size()>0){
							iterator.remove();
						}
						break;
					}
				}
			}

		}
		if (groupCodes.size()>0){
			criteria.addCriterion("itemGroupCode",Operator.IN,groupCodes);
		}
		Page<Item> items = itemSerivce.listPage(Item.class, page, criteria);
		List<Item> content = items.getContent();
		List<ItemWithSubExtendsVO> returnContent = new ArrayList<>();

		if (content.size()>0){
			List<String> itemCodes = content.stream().map(Item::getItemCode).collect(Collectors.toList());

			List<ItemLeadTimeProp> leadTimeProps =  JpaUtil.linq(ItemLeadTimeProp.class).equal("propType", "item").in("code", itemCodes).list();
			Map<String, ItemLeadTimeProp> leadTimePropMap = JpaUtil.index(leadTimeProps,"code");

			List<ItemPlanProp> planProps =  JpaUtil.linq(ItemPlanProp.class).equal("propType", "item").in("code", itemCodes).list();
			Map<String, ItemPlanProp> planPropMap = JpaUtil.index(planProps,"code");

			List<ItemPurchaseProp> purchaseProps =  JpaUtil.linq(ItemPurchaseProp.class).equal("propType", "item").in("code", itemCodes).list();
			Map<String, ItemPurchaseProp> purchasePropMap = JpaUtil.index(purchaseProps,"code");

			List<ItemStoreProp> storeProps =  JpaUtil.linq(ItemStoreProp.class).equal("propType", "item").in("code", itemCodes).list();
			Map<String, ItemStoreProp> storePropMap = JpaUtil.index(storeProps,"code");

			List<ItemMaterialProp> materialProps =  JpaUtil.linq(ItemMaterialProp.class).equal("propType", "item").in("code", itemCodes).list();
			Map<String, ItemMaterialProp> materialPropMap = JpaUtil.index(materialProps,"code");
			for (Item item:content){
				ItemWithSubExtendsVO extendsVO = new ItemWithSubExtendsVO();
				BeanReflectionUtils.copyProperties(extendsVO, item);

				String itemCode = item.getItemCode();
				extendsVO.setItemLeadTimeProp(leadTimePropMap.get(itemCode));
				extendsVO.setItemPlanProp(planPropMap.get(itemCode));
				extendsVO.setItemPurchaseProp(purchasePropMap.get(itemCode));
				extendsVO.setItemStoreProp(storePropMap.get(itemCode));
				extendsVO.setItemMaterialProp(materialPropMap.get(itemCode));
				returnContent.add(extendsVO);
			}
		}
		return Result.OK(new PageImpl<ItemWithSubExtendsVO>(returnContent, page, items.getTotalElements()));
	}


	@GetMapping("list/{itemCode}")
	@Operation(summary = "根据itemCode获取物料", description = "根据itemCode获取物料", method = "GET")
	public Result<Item> getById(@PathVariable(name = "itemCode", required = true) String itemCode) {
		Item item = itemSerivce.getById(Item.class, itemCode);
		return Result.OK(item);
	}
	@GetMapping("listbycodes/{itemCodes}")
	@Operation(summary = "根据itemCodes获取物料", description = "根据itemCodes获取物料", method = "GET")
	public Result<List<Item>> listbycodes(@PathVariable(name = "itemCodes", required = true) String itemCodes) {
		if (StringUtils.isBlank(itemCodes)){
			return Result.error("查询codes为空");
		}
		String[] codes = itemCodes.split(",");//Stream.of(split).collect(Collectors.toList());
		Criteria criteria = Criteria.create();
		criteria.addCriterion("itemCode",Operator.IN, Stream.of(codes).collect(Collectors.toList()));
		return Result.OK(itemSerivce.list(Item.class,criteria));
	}


	@GetMapping("listWithSubExtends/{itemCode}")
	@Operation(summary = "根据itemCode获取物料（带扩展子表信息）", description = "根据itemCode获取物料（带扩展子表信息）", method = "GET")
	public Result<ItemWithSubExtendsVO> queryItemWithExtendsByCode(@PathVariable(name = "itemCode", required = true) String itemCode) {
		return itemSerivce.queryItemWithExtendsByCode(itemCode);
	}
	@PostMapping("add")
	@Operation(summary = "新增物料", description = "新增物料", method = "POST")
	public Result<Item> add(@RequestBody Item item) {
		itemSerivce.save(item);
		return Result.OK(item);
	}
	
	@PutMapping("edit")
	@Operation(summary = "编辑物料", description = "编辑物料（全量）", method = "PUT")
	public Result<Item> edit(@RequestBody Item item) {
		itemSerivce.update(item);
		return Result.OK(item);
	}
	
	@DeleteMapping("remove/{itemCode}")
	@Operation(summary = "删除物料", description = "删除物料", method = "DELETE")
	@Transactional(readOnly = false)
	public Result<Item> remove(@PathVariable(name = "itemCode", required = true) String itemCode) {
		String[] itemCodes = itemCode.split(",");
		String msg = itemSerivce.deleteCheck(itemCode);
		if (StringUtils.isNotBlank(msg)){
			return Result.error(msg);
		}
		for(String key : itemCodes){
			itemSerivce.delete(Item.class, key,itemDeletePolicy);
		}
		return Result.OK();
	}

	//递归查询物料组
	/*private ItemGroup getItemGroupFromList(List<ItemGroup> list,String groupCode){
		if (list==null||list.size()==0||StringUtils.isBlank(groupCode)){
			return null;
		}
		ItemGroup returnGroup = null;
		for (ItemGroup group:list){
			if (group.getGroupCode().equals(groupCode)){
				returnGroup = group;
				return returnGroup;
			}else{
				if (group.getChildren()!=null &&group.getChildren().size()>0){
					returnGroup =  getItemGroupFromList(group.getChildren(),groupCode);
					if (returnGroup!=null){
						break;
					}
				}
			}
		}
		return returnGroup;
	}

	//递归查询物料组及子物料组对应的groupcode
	private void getAllGroupCodeFromItemGroup(List<String> groupCodes,ItemGroup itemGroup){
		if (itemGroup==null){
			return ;
		}
		//List<String> groupCodes = new ArrayList<>();
		groupCodes.add(itemGroup.getGroupCode());
		if (itemGroup.getChildren()!=null&&itemGroup.getChildren().size()>0){
			for (ItemGroup group:itemGroup.getChildren()){
				getAllGroupCodeFromItemGroup(groupCodes,group);
			}
		}
	}*/

	@PostMapping("list/batch/submit")
	@Operation(summary = "批量提交", description = "批量提交", method = "POST")
	public Result<?> getBatchSubmit(@RequestBody List<Item> items) {
		return  itemSerivce.batchSubmit(items);
		
	}
}
